package com.leo.controller;


import com.leo.mapper.DepartmentMapper;
import com.leo.pojo.Department;
import com.leo.pojo.Employee;
import com.leo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    public EmployeeService employeeService;

    @Autowired
    DepartmentMapper departmentMapper;

    @RequestMapping("/emp")
    public String list(Model model){
        Collection<Employee> employees = employeeService.getAll();
        model.addAttribute("empList",employees);
        return "/emp/list";
    }

    @RequestMapping("/toAdd")
    public String toAddPage(Model model){
        Collection<Department> departments = departmentMapper.getAllDepartment();
        model.addAttribute("departments",departments);
        return "/emp/add";
    }
    @PostMapping("/toAdd")
    public String toAddPage(Employee employee){
        employeeService.save(employee);
        return "redirect:/emp";
    }
    @RequestMapping("/toUpdate/{id}")
    public String toUpdatePage(@PathVariable("id") Integer id,Model model){

        Employee employee = employeeService.getEmployeeById(id);
        Collection<Department> departments = departmentMapper.getAllDepartment();
        model.addAttribute("departments",departments);
        model.addAttribute("employee",employee);
        return "/emp/update";
    }
    @RequestMapping("/update")
    public String update(Employee employee,Model model){
        employeeService.update(employee);
        /*Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("empList",employees);*/
        return list(model);
    }
}
